{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "4295e8c1",
   "metadata": {},
   "source": [
    "# 第二讲 字符串（一）"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "76c4188a",
   "metadata": {},
   "source": [
    "## 1. 什么是字符串？\n",
    "\n",
    "**字符串（string）** 就是一系列字符。在编程中，字符串是最基本也是最重要的数据类型之一。\n",
    "\n",
    "## 2. 为什么字符串重要？\n",
    "\n",
    "- **数据处理基础**：大多数程序会定义并收集某种数据，然后使用它们来做些有意义的事情\n",
    "- **数据分类的必要性**：对数据分类大有裨益\n",
    "- **看似简单，功能强大**：字符串虽然看似简单，但能够以很多不同的方式使用\n",
    "\n",
    "## 3. Python中的字符串定义\n",
    "\n",
    "### 3.1 基本语法\n",
    "\n",
    "在Python中，**用引号引起的都是字符串**，引号可以是：\n",
    "\n",
    "- **单引号** `'`\n",
    "- **双引号** `\"`\n",
    "\n",
    "### 3.2 基本示例"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cf91a278",
   "metadata": {},
   "outputs": [],
   "source": [
    "\"This is a string.\"\n",
    "'This is also a string.'"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b9fb1be8",
   "metadata": {},
   "source": [
    "## 引号的灵活使用\n",
    "\n",
    "### 引号选择的灵活性\n",
    "\n",
    "Python允许使用单引号或双引号定义字符串，这种灵活性带来了很大的便利：\n",
    "\n",
    "#### 1. 在字符串中包含引号\n",
    "\n",
    "```python\n",
    "# 使用单引号包围，内部可以包含双引号\n",
    "'I told my friend, \"Python is my favorite language!\"'\n",
    "\n",
    "# 使用双引号包围，内部可以包含单引号\n",
    "\"The language 'Python' is named after Monty Python, not the snake.\"\n",
    "```\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4a829f9c",
   "metadata": {},
   "source": [
    "#### 2. 在字符串中包含撇号\n",
    "\n",
    "```python\n",
    "# 使用双引号包围，可以包含撇号（单引号）\n",
    "\"One of Python's strengths is its diverse and supportive community.\"\n",
    "```\n",
    "\n",
    "## "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "33cfbc42",
   "metadata": {},
   "source": [
    "## 4. 使用方法修改字符串的大小写\n",
    "\n",
    "### 4.1 什么是字符串方法？\n",
    "\n",
    "#### (1) 方法的定义\n",
    "\n",
    "**方法（method）** 是Python可对数据执行的操作。\n",
    "\n",
    "#### (2) 方法调用语法\n",
    "\n",
    "变量名.方法名()\n",
    "\n",
    "- **句点（.）**：让Python对变量执行指定的方法\n",
    "- **括号（）**：方法后面都跟着一对括号，用于提供额外信息\n",
    "- **空括号**：如果方法不需要额外信息，括号为空\n",
    "\n",
    "### 4.2 三种基本的大小写方法\n",
    "\n",
    "#### (1) title() 方法 - 标题格式\n",
    "\n",
    "将每个单词的首字母改为大写"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "c93dab36",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Ada Lovelace\n"
     ]
    }
   ],
   "source": [
    "# name.py\n",
    "name = \"ada lovelace\"\n",
    "print(name.title())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f80a2077",
   "metadata": {},
   "source": [
    "#### (2) upper() 方法 - 全大写\n",
    "\n",
    "将字符串中的所有字母转换为大写"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "13ee701c",
   "metadata": {},
   "outputs": [],
   "source": [
    "name = \"Ada Lovelace\"\n",
    "print(name.upper())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "4a28786c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "重要通知\n",
      "DATABASE_URL\n"
     ]
    }
   ],
   "source": [
    "# 创建醒目的标题\n",
    "title = \"重要通知\"\n",
    "print(title.upper())  \n",
    "\n",
    "# 处理常量或配置\n",
    "config_key = \"database_url\"\n",
    "print(config_key.upper()) "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bcfbb1f9",
   "metadata": {},
   "source": [
    "#### (3) lower() 方法 - 全小写\n",
    "\n",
    "将字符串中的所有字母转换为小写"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "bed8246e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ada lovelace\n"
     ]
    }
   ],
   "source": [
    "name = \"Ada Lovelace\"\n",
    "print(name.lower())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "cf111ec5",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "user@example.com\n",
      "用户确认了操作\n"
     ]
    }
   ],
   "source": [
    "# 用户输入标准化\n",
    "email = \"USER@EXAMPLE.COM\"\n",
    "normalized_email = email.lower()\n",
    "print(normalized_email)  # 输出：user@example.com\n",
    "\n",
    "# 大小写不敏感的比较\n",
    "user_input = \"YES\"\n",
    "if user_input.lower() == \"yes\":\n",
    "    print(\"用户确认了操作\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "002bd4a4",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "原始字符串: ada lovelace\n",
      "标题格式: Ada Lovelace\n",
      "全大写: ADA LOVELACE\n",
      "全小写: ada lovelace\n"
     ]
    }
   ],
   "source": [
    "# 演示所有三种方法\n",
    "name = \"ada lovelace\"\n",
    "\n",
    "print(\"原始字符串:\", name)\n",
    "print(\"标题格式:\", name.title())\n",
    "print(\"全大写:\", name.upper())\n",
    "print(\"全小写:\", name.lower())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b64a9761",
   "metadata": {},
   "source": [
    "#### (4) 实际应用场景\n",
    "\n",
    "1. 数据标准化存储\n",
    "    用户输入的数据大小写不统一：\n",
    "    - `Ada`、`ADA`、`ada` 应该被视为同一个名字"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "3afceb11",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "存储的名字: ['ada', 'ada', 'ada', 'ada']\n",
      "显示格式: Ada\n",
      "显示格式: Ada\n",
      "显示格式: Ada\n",
      "显示格式: Ada\n"
     ]
    }
   ],
   "source": [
    "# 存储时统一转换为小写\n",
    "def store_user_name(name):\n",
    "    return name.lower()\n",
    "\n",
    "# 显示时转换为合适的格式\n",
    "def display_user_name(stored_name):\n",
    "    return stored_name.title()\n",
    "\n",
    "# 示例使用\n",
    "user_inputs = [\"Ada\", \"ADA\", \"ada\", \"AdA\"]\n",
    "stored_names = []\n",
    "\n",
    "for name in user_inputs:\n",
    "    stored_names.append(store_user_name(name))\n",
    "\n",
    "print(\"存储的名字:\", stored_names)\n",
    "# 输出：存储的名字: ['ada', 'ada', 'ada', 'ada']\n",
    "\n",
    "for stored_name in stored_names:\n",
    "    print(\"显示格式:\", display_user_name(stored_name))\n",
    "# 输出：显示格式: Ada (重复4次)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "228f6606",
   "metadata": {},
   "source": [
    "2. 用户界面友好显示"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "21501aac",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "产品标题: Python Programming Book\n",
      "警告: SYSTEM ERROR DETECTED\n"
     ]
    }
   ],
   "source": [
    "# 产品名称格式化\n",
    "product_name = \"python programming book\"\n",
    "print(\"产品标题:\", product_name.title())\n",
    "# 输出：产品标题: Python Programming Book\n",
    "\n",
    "# 警告信息\n",
    "warning = \"system error detected\"\n",
    "print(\"警告:\", warning.upper())\n",
    "# 输出：警告: SYSTEM ERROR DETECTED"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4b8fe67d",
   "metadata": {},
   "source": [
    "3. 数据比较和验证"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "bc9ad60c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "有效命令\n"
     ]
    }
   ],
   "source": [
    "# 大小写不敏感的密码验证（简化示例）\n",
    "def check_command(user_input, valid_commands):\n",
    "    user_input_lower = user_input.lower()\n",
    "    valid_commands_lower = [cmd.lower() for cmd in valid_commands]\n",
    "    return user_input_lower in valid_commands_lower\n",
    "\n",
    "# 测试\n",
    "commands = [\"START\", \"stop\", \"Pause\", \"RESUME\"]\n",
    "user_command = \"start\"\n",
    "\n",
    "if check_command(user_command, commands):\n",
    "    print(\"有效命令\")\n",
    "else:\n",
    "    print(\"无效命令\")\n",
    "# 输出：有效命令"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4012d976",
   "metadata": {},
   "source": [
    "### 4.3 方法的重要特性"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5f4ce35d",
   "metadata": {},
   "source": [
    "1. 不修改原字符串"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "0698d4a1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "原字符串: Hello World\n",
      "大写版本: HELLO WORLD\n"
     ]
    }
   ],
   "source": [
    "original = \"Hello World\"\n",
    "uppercase = original.upper()\n",
    "\n",
    "print(\"原字符串:\", original)     \n",
    "print(\"大写版本:\", uppercase)  "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a217a852",
   "metadata": {},
   "source": [
    "2. 可以链式调用"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "9ef0b18d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Ada Lovelace\n"
     ]
    }
   ],
   "source": [
    "name = \"  ada lovelace  \"\n",
    "formatted = name.strip().title()\n",
    "print(formatted)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1f6c2a0b",
   "metadata": {},
   "source": [
    "3. 返回新字符串"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "fc566fb7",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "原文本：python\n",
      "结果：PYTHON\n"
     ]
    }
   ],
   "source": [
    "text = \"python\"\n",
    "result = text.upper()\n",
    "print(f\"原文本：{text}\")   \n",
    "print(f\"结果：{result}\")  "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4e1f977b",
   "metadata": {},
   "source": [
    "### [进阶练习]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "baae1260",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "John Doe\n",
      "Jane Smith\n"
     ]
    }
   ],
   "source": [
    "# 练习：创建一个姓名处理函数\n",
    "def format_full_name(first_name, last_name):\n",
    "    \"\"\"格式化全名为标题格式\"\"\"\n",
    "    formatted_first = first_name.title()\n",
    "    formatted_last = last_name.title()\n",
    "    return f\"{formatted_first} {formatted_last}\"\n",
    "\n",
    "# 测试函数\n",
    "print(format_full_name(\"john\", \"doe\"))      # John Doe\n",
    "print(format_full_name(\"JANE\", \"smith\"))    # Jane Smith"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e8adfa56",
   "metadata": {},
   "source": [
    "### 4.4 小结\n",
    "\n",
    "#### 核心知识点\n",
    "\n",
    "- **方法调用语法**：`变量名.方法名()`\n",
    "- **三种基本方法**：\n",
    "  - `title()`：首字母大写\n",
    "  - `upper()`：全大写\n",
    "  - `lower()`：全小写\n",
    "\n",
    "#### 实用价值\n",
    "\n",
    "- **数据标准化**：统一存储格式\n",
    "- **用户体验**：友好的显示格式\n",
    "- **数据处理**：大小写不敏感的比较\n",
    "\n",
    "#### 最佳实践\n",
    "\n",
    "- **存储时使用 `lower()`**：确保数据一致性\n",
    "- **显示时使用 `title()`**：提供友好的用户界面\n",
    "- **比较时使用 `lower()`**：实现大小写不敏感的匹配\n",
    "\n",
    "> **重要提示**：字符串方法不会修改原始字符串，而是返回一个新的字符串。这是Python字符串不可变性的体现。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "01e58abe",
   "metadata": {},
   "source": [
    "## 5. 在字符串中使用变量\n",
    "\n",
    "### 5.1 什么是f字符串？\n",
    "#### (1) 定义\n",
    "\n",
    "**f字符串（f-string）** 是Python中一种格式化字符串的方法，允许在字符串中直接插入变量的值。\n",
    "\n",
    "#### (2) 名称来源\n",
    "\n",
    "- **f** 是 **format**（设置格式）的简写\n",
    "- Python通过把花括号内的变量替换为其值来设置字符串的格式\n",
    "\n",
    "### 5.2 f字符串的基本语法\n",
    "\n",
    "#### (1) 语法格式\n",
    "\n",
    "> f\"字符串内容 {变量名} 更多内容\"\n",
    "\n",
    "#### (2) 关键要素\n",
    "\n",
    "1. **f前缀**：在左引号前加上字母 `f`\n",
    "2. **花括号**：`{}` 用于包围要插入的变量\n",
    "3. **变量替换**：Python自动将花括号内的变量替换为其值"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "10a8e30e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "This guy's first name is Ada, and her last name is Lovelace.\n",
      "Hello, Ada Lovelace!\n"
     ]
    }
   ],
   "source": [
    "# full_name.py\n",
    "first_name = \"ada\"\n",
    "last_name = \"lovelace\"\n",
    "full_name = f\"This guy's first name is {first_name.title()}, and her last name is {last_name.title()}.\"\n",
    "print(full_name)\n",
    "\n",
    "full_name = f\"{first_name} {last_name}\"\n",
    "print(f\"Hello, {full_name.title()}!\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "3095ebcc",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "用户名：张三，年龄：25岁，所在城市：北京\n"
     ]
    }
   ],
   "source": [
    "# 用户资料展示\n",
    "username = \"张三\"\n",
    "age = 25\n",
    "city = \"北京\"\n",
    "\n",
    "profile = f\"用户名：{username}，年龄：{age}岁，所在城市：{city}\"\n",
    "print(profile)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "b6d71347",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "backup_2025-10-02.txt\n"
     ]
    }
   ],
   "source": [
    "# 生成带时间戳的文件名\n",
    "import datetime\n",
    "\n",
    "date = datetime.date.today()\n",
    "file_type = \"backup\"\n",
    "filename = f\"{file_type}_{date}.txt\"\n",
    "print(filename)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "bc5e2fb9",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "产品：Python编程书\n",
      "数量：150本\n",
      "单价：¥89.9\n",
      "总计：¥13485.00\n"
     ]
    }
   ],
   "source": [
    "# 销售报告\n",
    "product = \"Python编程书\"\n",
    "quantity = 150\n",
    "price = 89.9\n",
    "total = quantity * price\n",
    "\n",
    "report = f\"产品：{product}\\n数量：{quantity}本\\n单价：¥{price}\\n总计：¥{total:.2f}\"\n",
    "print(report)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "3ffd6a86",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "https://api.example.com/v1/users/12345\n"
     ]
    }
   ],
   "source": [
    "# 动态URL构建\n",
    "base_url = \"https://api.example.com\"\n",
    "version = \"v1\"\n",
    "endpoint = \"users\"\n",
    "user_id = 12345\n",
    "\n",
    "api_url = f\"{base_url}/{version}/{endpoint}/{user_id}\"\n",
    "print(api_url)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b4af7c11",
   "metadata": {},
   "source": [
    "### 5.3 f字符串的高级特性"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a9b1f837",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "矩形面积：50平方米\n"
     ]
    }
   ],
   "source": [
    "# 在f字符串中进行计算\n",
    "length = 10\n",
    "width = 5\n",
    "print(f\"矩形面积：{length * width}平方米\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "39676386",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "考试结果：及格\n"
     ]
    }
   ],
   "source": [
    "# 条件判断\n",
    "score = 85\n",
    "result = f\"考试结果：{'及格' if score >= 60 else '不及格'}\"\n",
    "print(result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "832ff0a2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "π的值约为：3.14\n",
      "增长率：12.3%\n"
     ]
    }
   ],
   "source": [
    "# 数字格式化\n",
    "pi = 3.14159265359\n",
    "print(f\"π的值约为：{pi:.2f}\")\n",
    "\n",
    "# 百分比格式\n",
    "rate = 0.1234\n",
    "print(f\"增长率：{rate:.1%}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d4fed6fb",
   "metadata": {},
   "source": [
    "#### 格式化语法总结\n",
    "> f-string 的基本语法：f\"{value:format_spec}\"\n",
    "\n",
    "> 格式说明符的结构：[[fill]align][sign][#][0][width][,][.precision][type]\n",
    "\n",
    "- fill: 填充字符\n",
    "- align: 对齐方式 (< 左对齐, > 右对齐, ^ 居中)\n",
    "- sign: 符号显示 (+ 总是显示, - 仅负数显示)\n",
    "- width: 最小宽度\n",
    "- ,: 千位分隔符\n",
    "- precision: 精度\n",
    "- type: 类型 (d 整数, f 浮点, % 百分比, e 科学计数法等)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "84935944",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3.14\n",
      "3.1416\n",
      "      3.14\n"
     ]
    }
   ],
   "source": [
    "# 小数位数控制\n",
    "pi = 3.14159265359\n",
    "print(f\"{pi:.2f}\")      # 3.14 (保留2位小数)\n",
    "print(f\"{pi:.4f}\")      # 3.1416 (保留4位小数)\n",
    "print(f\"{pi:10.2f}\")    # \"      3.14\" (总宽度10，右对齐)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "id": "0e2d20d6",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "42\n",
      "0042\n",
      "101010\n",
      "52\n",
      "2a\n",
      "2A\n"
     ]
    }
   ],
   "source": [
    "# 整数格式化\n",
    "num = 42\n",
    "print(f\"{num:d}\")       # 42 (十进制)\n",
    "print(f\"{num:04d}\")     # 0042 (4位数，前面补0)\n",
    "print(f\"{num:b}\")       # 101010 (二进制)\n",
    "print(f\"{num:o}\")       # 52 (八进制)\n",
    "print(f\"{num:x}\")       # 2a (十六进制小写)\n",
    "print(f\"{num:X}\")       # 2A (十六进制大写)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "id": "8b793c52",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1.234568e+08\n",
      "1.234568E+08\n",
      "1.23e+08\n"
     ]
    }
   ],
   "source": [
    "# 科学计数法\n",
    "big_num = 123456789\n",
    "print(f\"{big_num:e}\")   # 1.234568e+08\n",
    "print(f\"{big_num:E}\")   # 1.234568E+08\n",
    "print(f\"{big_num:.2e}\") # 1.23e+08"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "id": "78eb3ff7",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "12.3%\n",
      "12.34%\n",
      "86%\n"
     ]
    }
   ],
   "source": [
    "# 百分比\n",
    "rate = 0.1234\n",
    "print(f\"{rate:.1%}\")    # 12.3%\n",
    "print(f\"{rate:.2%}\")    # 12.34%\n",
    "\n",
    "efficiency = 0.856\n",
    "print(f\"{efficiency:.0%}\")  # 86%"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "id": "63d87f2e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1,234,567\n",
      "1,234,567.00\n",
      "$1,234.56\n"
     ]
    }
   ],
   "source": [
    "# 千位分隔符\n",
    "large_num = 1234567\n",
    "print(f\"{large_num:,}\")     # 1,234,567\n",
    "print(f\"{large_num:,.2f}\")  # 1,234,567.00\n",
    "\n",
    "# 货币格式示例\n",
    "price = 1234.56\n",
    "print(f\"${price:,.2f}\")     # $1,234.56"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "id": "68e3a14d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello     \n",
      "     Hello\n",
      "  Hello   \n",
      "**Hello***\n",
      "This is a \n"
     ]
    }
   ],
   "source": [
    "# 对齐方式\n",
    "text = \"Hello\"\n",
    "print(f\"{text:<10}\")    # \"Hello     \" (左对齐)\n",
    "print(f\"{text:>10}\")    # \"     Hello\" (右对齐)\n",
    "print(f\"{text:^10}\")    # \"  Hello   \" (居中对齐)\n",
    "print(f\"{text:*^10}\")   # \"**Hello***\" (居中，用*填充)\n",
    "\n",
    "# 字符串截断和填充\n",
    "long_text = \"This is a very long string\"\n",
    "print(f\"{long_text:.10}\")   # \"This is a \" (截断到10个字符)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "id": "61369637",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2025-10-02\n",
      "2025-10-02 20:28\n",
      "October 02, 2025\n",
      "Thursday\n"
     ]
    }
   ],
   "source": [
    "# 日期时间格式化\n",
    "from datetime import datetime\n",
    "\n",
    "now = datetime.now()\n",
    "print(f\"{now:%Y-%m-%d}\")        # 2024-03-15\n",
    "print(f\"{now:%Y-%m-%d %H:%M}\")  # 2024-03-15 14:30\n",
    "print(f\"{now:%B %d, %Y}\")       # March 15, 2024\n",
    "print(f\"{now:%A}\")              # Friday"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "id": "8fbebcac",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3.142\n",
      "    test\n",
      "x + y = 30\n",
      "x * y = 200\n"
     ]
    }
   ],
   "source": [
    "# 动态格式控制\n",
    "precision = 3\n",
    "value = 3.14159\n",
    "print(f\"{value:.{precision}f}\")  # 3.142\n",
    "\n",
    "width = 8\n",
    "text = \"test\"\n",
    "print(f\"{text:>{width}}\")        # \"    test\"\n",
    "\n",
    "# 格式化表达式\n",
    "x, y = 10, 20\n",
    "print(f\"{x + y = }\")            # x + y = 30\n",
    "print(f\"{x * y = :,}\")          # x * y = 200"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "id": "e9a6f13d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "张三        25  12,345.67\n",
      "进度: 75.0% ███████████████     \n",
      "总计: ¥   98,765.43\n"
     ]
    }
   ],
   "source": [
    "# 常用格式化模板\n",
    "\n",
    "# 表格格式\n",
    "name = \"张三\"\n",
    "age = 25\n",
    "salary = 12345.67\n",
    "print(f\"{name:<8} {age:>3} {salary:>10,.2f}\")\n",
    "# 张三        25  12,345.67\n",
    "\n",
    "# 进度显示\n",
    "progress = 0.75\n",
    "print(f\"进度: {progress:.1%} {'█' * int(progress * 20):20}\")\n",
    "# 进度: 75.0% ███████████████     \n",
    "\n",
    "# 数据汇总\n",
    "total = 98765.43\n",
    "print(f\"总计: ¥{total:>12,.2f}\")\n",
    "# 总计: ¥   98,765.43"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f1b77ea8",
   "metadata": {},
   "source": [
    "### 5.4 最佳实践"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3ec40dc9",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. 变量命名清晰\n",
    "# 推荐：使用有意义的变量名\n",
    "first_name = \"李\"\n",
    "last_name = \"明\"\n",
    "full_name = f\"{first_name}{last_name}\"\n",
    "\n",
    "# 不推荐：使用模糊的变量名\n",
    "a = \"李\"\n",
    "b = \"明\"\n",
    "c = f\"{a}{b}\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "29be0d8c",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 2. 复杂表达式的处理\n",
    "# 对于复杂计算，先计算再插入\n",
    "price = 100\n",
    "tax_rate = 0.08\n",
    "discount = 0.1\n",
    "\n",
    "# 推荐：分步计算\n",
    "tax = price * tax_rate\n",
    "discounted_price = price * (1 - discount)\n",
    "final_price = discounted_price + tax\n",
    "message = f\"最终价格：¥{final_price:.2f}\"\n",
    "\n",
    "# 不推荐：在f字符串中进行复杂计算\n",
    "message = f\"最终价格：¥{price * (1 - discount) + price * tax_rate:.2f}\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a179df2c",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 3. 长字符串的处理\n",
    "# 使用多行f字符串\n",
    "name = \"张三\"\n",
    "department = \"技术部\"\n",
    "position = \"高级工程师\"\n",
    "\n",
    "# 方法1：使用三引号\n",
    "info = f\"\"\"\n",
    "员工信息：\n",
    "姓名：{name}\n",
    "部门：{department}\n",
    "职位：{position}\n",
    "\"\"\"\n",
    "\n",
    "# 方法2：分行组合\n",
    "info = (f\"员工信息：\\n\"\n",
    "        f\"姓名：{name}\\n\"\n",
    "        f\"部门：{department}\\n\"\n",
    "        f\"职位：{position}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1d96b84e",
   "metadata": {},
   "source": [
    "### 5.5 小结\n",
    "\n",
    "#### (1) 核心知识点\n",
    "\n",
    "- **f字符串语法**：`f\"内容 {变量} 内容\"`\n",
    "- **变量插入**：使用花括号 `{}` 包围变量名\n",
    "- **方法调用**：可在花括号内直接调用方法\n",
    "- **表达式支持**：支持在花括号内进行计算\n",
    "\n",
    "#### (2) 实用价值\n",
    "\n",
    "- **提高效率**：简化字符串格式化过程\n",
    "- **增强可读性**：变量直接出现在使用位置\n",
    "- **功能强大**：支持复杂的格式化需求\n",
    "- **性能优越**：比传统方法执行更快\n",
    "\n",
    "#### (3) 使用建议\n",
    "\n",
    "- **优先选择**：在Python 3.6+中优先使用f字符串\n",
    "- **保持简洁**：避免在花括号内进行过于复杂的操作\n",
    "- **合理分行**：对于长字符串，适当分行提高可读性\n",
    "\n",
    "> **重要提示**：f字符串是现代Python中字符串格式化的首选方法，它结合了简洁的语法和强大的功能，是每个Python程序员都应该掌握的重要技能。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "38358648",
   "metadata": {},
   "source": [
    "# Python 字符串格式化综合练习题\n",
    "\n",
    "## 题目：销售数据报表生成器\n",
    "\n",
    "某公司需要生成一份销售数据报表，请根据以下要求完成代码：\n",
    "\n",
    "### 数据源\n",
    "```python\n",
    "# 销售数据\n",
    "sales_data = [\n",
    "    {\"name\": \"张三\", \"region\": \"华北\", \"sales\": 1234567.89, \"target\": 1200000, \"join_date\": \"2023-03-15\"},\n",
    "    {\"name\": \"李四\", \"region\": \"华东\", \"sales\": 987654.32, \"target\": 1000000, \"join_date\": \"2022-08-20\"},\n",
    "    {\"name\": \"王五\", \"region\": \"华南\", \"sales\": 1456789.01, \"target\": 1300000, \"join_date\": \"2023-01-10\"},\n",
    "    {\"name\": \"赵六\", \"region\": \"西南\", \"sales\": 876543.21, \"target\": 900000, \"join_date\": \"2022-12-05\"},\n",
    "]\n",
    "\n",
    "from datetime import datetime, date\n",
    "report_date = datetime(2024, 3, 15, 14, 30, 45)\n",
    "```\n",
    "\n",
    "### 要求输出格式\n",
    "\n",
    "请编写代码生成如下格式的报表：\n",
    "\n",
    "```\n",
    "================== 销售业绩报表 ==================\n",
    "报表生成时间: 2024年03月15日 14:30:45\n",
    "\n",
    "┌──────────────────────────────────────────────────────────────────────────┐\n",
    "│                              销售员业绩统计                               │\n",
    "├──────┬──────┬──────────────┬──────────────┬────────┬──────────────────────┤\n",
    "│ 姓名 │ 地区 │   实际销售   │   目标销售   │完成率  │       入职时间       │\n",
    "├──────┼──────┼──────────────┼──────────────┼────────┼──────────────────────┤\n",
    "│ 张三 │ 华北 │  ¥1,234,568  │  ¥1,200,000  │ 102.9% │ 2023-03-15 (365天)   │\n",
    "│ 李四 │ 华东 │    ¥987,654  │  ¥1,000,000  │  98.8% │ 2022-08-20 (573天)   │\n",
    "│ 王五 │ 华南 │  ¥1,456,789  │  ¥1,300,000  │ 112.1% │ 2023-01-10 (430天)   │\n",
    "│ 赵六 │ 西南 │    ¥876,543  │    ¥900,000  │  97.4% │ 2022-12-05 (466天)   │\n",
    "└──────┴──────┴──────────────┴──────────────┴────────┴──────────────────────┘\n",
    "\n",
    "业绩汇总:\n",
    "• 总销售额: ¥4,555,554 (目标: ¥4,400,000)\n",
    "• 整体完成率: 103.5%\n",
    "• 超额完成人数: 2人 (占比: 50.0%)\n",
    "• 平均销售额: ¥1,138,889\n",
    "\n",
    "最佳销售员: 王五 (华南) - ¥1,456,789\n",
    "最低销售员: 赵六 (西南) - ¥876,543\n",
    "\n",
    "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n",
    "报表生成完成 | 数据统计日期: 2024-03-15\n",
    "```\n",
    "\n",
    "### 挑战要求\n",
    "\n",
    "1. **表格对齐**: 使用合适的字符串格式化确保表格整齐对齐\n",
    "2. **数字格式**: 金额显示千位分隔符，百分比保留1位小数\n",
    "3. **日期处理**: 计算入职天数（从入职日期到报表生成日期）\n",
    "4. **数据统计**: 计算总销售额、平均值、完成率等\n",
    "5. **条件格式**: 找出最佳和最低销售员\n",
    "6. **美观输出**: 使用表格边框字符美化输出\n",
    "\n",
    "### 提示\n",
    "- 使用 `datetime.strptime()` 解析日期字符串\n",
    "- 计算日期差可以用 `(date1 - date2).days`\n",
    "- 表格边框可以使用 Unicode 字符：`┌┐└┘├┤┬┴┼─│`\n",
    "- 考虑使用循环和字符串格式化组合\n",
    "\n",
    "---\n",
    "\n",
    "**开始编程吧！看看你能否完美实现这个综合格式化挑战！** 🚀"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d0cc5a83",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "================== 销售业绩报表 ==================\n",
      "报表生成时间: 2024年03月15日 14:30:45\n",
      "\n",
      "┌──────────────────────────────────────────────────────────────────────────┐\n",
      "│                                销售员业绩统计                                 │\n",
      "├──────┬──────┬──────────────┬──────────────┬────────┬──────────────────────┤\n",
      "│  姓名  │  地区  │     实际销售     │     目标销售     │  完成率   │         入职时间         │\n",
      "├──────┼──────┼──────────────┼──────────────┼────────┼──────────────────────┤\n",
      "│  张三  │  华北  │¥   1,234,568│¥   1,200,000│ 102.9%│2023-03-15 (366天)   │\n",
      "│  李四  │  华东  │¥     987,654│¥   1,000,000│  98.8%│2022-08-20 (573天)   │\n",
      "│  王五  │  华南  │¥   1,456,789│¥   1,300,000│ 112.1%│2023-01-10 (430天)   │\n",
      "│  赵六  │  西南  │¥     876,543│¥     900,000│  97.4%│2022-12-05 (466天)   │\n",
      "└──────┴──────┴──────────────┴──────────────┴────────┴──────────────────────┘\n",
      "\n",
      "业绩汇总:\n",
      "• 总销售额: ¥4,555,554 (目标: ¥4,400,000)\n",
      "• 整体完成率: 103.5%\n",
      "• 超额完成人数: 2人 (占比: 50.0%)\n",
      "• 平均销售额: ¥1,138,889\n",
      "\n",
      "最佳销售员: 王五 (华南) - ¥1,456,789\n",
      "最低销售员: 赵六 (西南) - ¥876,543\n",
      "\n",
      "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n",
      "报表生成完成 | 数据统计日期: 2024-03-15\n"
     ]
    }
   ],
   "source": [
    "# 销售数据报表生成器 - 参考代码\n",
    "\n",
    "from datetime import datetime\n",
    "\n",
    "# 销售数据\n",
    "sales_data = [\n",
    "    {\"name\": \"张三\", \"region\": \"华北\", \"sales\": 1234567.89, \"target\": 1200000, \"join_date\": \"2023-03-15\"},\n",
    "    {\"name\": \"李四\", \"region\": \"华东\", \"sales\": 987654.32, \"target\": 1000000, \"join_date\": \"2022-08-20\"},\n",
    "    {\"name\": \"王五\", \"region\": \"华南\", \"sales\": 1456789.01, \"target\": 1300000, \"join_date\": \"2023-01-10\"},\n",
    "    {\"name\": \"赵六\", \"region\": \"西南\", \"sales\": 876543.21, \"target\": 900000, \"join_date\": \"2022-12-05\"},\n",
    "]\n",
    "\n",
    "report_date = datetime(2024, 3, 15, 14, 30, 45)\n",
    "\n",
    "def generate_sales_report():\n",
    "    # 1. 报表头部\n",
    "    print(\"=\" * 18 + \" 销售业绩报表 \" + \"=\" * 18)\n",
    "    print(f\"报表生成时间: {report_date:%Y年%m月%d日 %H:%M:%S}\")\n",
    "    print()\n",
    "    \n",
    "    # 2. 表格头部\n",
    "    print(\"┌\" + \"─\" * 74 + \"┐\")\n",
    "    print(\"│\" + f\"{'销售员业绩统计':^72}\" + \"│\")\n",
    "    print(\"├\" + \"─\" * 6 + \"┬\" + \"─\" * 6 + \"┬\" + \"─\" * 14 + \"┬\" + \"─\" * 14 + \"┬\" + \"─\" * 8 + \"┬\" + \"─\" * 22 + \"┤\")\n",
    "    print(\"│\" + f\"{'姓名':^6}\" + \"│\" + f\"{'地区':^6}\" + \"│\" + f\"{'实际销售':^14}\" + \"│\" + f\"{'目标销售':^14}\" + \"│\" + f\"{'完成率':^8}\" + \"│\" + f\"{'入职时间':^22}\" + \"│\")\n",
    "    print(\"├\" + \"─\" * 6 + \"┼\" + \"─\" * 6 + \"┼\" + \"─\" * 14 + \"┼\" + \"─\" * 14 + \"┼\" + \"─\" * 8 + \"┼\" + \"─\" * 22 + \"┤\")\n",
    "    \n",
    "    # 3. 处理每行数据\n",
    "    total_sales = 0\n",
    "    total_target = 0\n",
    "    over_target_count = 0\n",
    "    \n",
    "    for person in sales_data:\n",
    "        # 解析入职日期并计算天数\n",
    "        join_date = datetime.strptime(person[\"join_date\"], \"%Y-%m-%d\")\n",
    "        days_worked = (report_date - join_date).days\n",
    "        \n",
    "        # 计算完成率\n",
    "        completion_rate = person[\"sales\"] / person[\"target\"]\n",
    "        if completion_rate >= 1.0:\n",
    "            over_target_count += 1\n",
    "        \n",
    "        # 累计统计\n",
    "        total_sales += person[\"sales\"]\n",
    "        total_target += person[\"target\"]\n",
    "        \n",
    "        # 格式化输出每一行\n",
    "        print(\"│\" + f\"{person['name']:^6}\" + \n",
    "              \"│\" + f\"{person['region']:^6}\" + \n",
    "              \"│\" + f\"¥{person['sales']:>12,.0f}\" + \n",
    "              \"│\" + f\"¥{person['target']:>12,.0f}\" + \n",
    "              \"│\" + f\"{completion_rate:>7.1%}\" + \n",
    "              \"│\" + f\"{person['join_date']} ({days_worked}天)\" + f\"{'':>3}\" + \n",
    "              \"│\")\n",
    "    \n",
    "    # 4. 表格底部\n",
    "    print(\"└\" + \"─\" * 6 + \"┴\" + \"─\" * 6 + \"┴\" + \"─\" * 14 + \"┴\" + \"─\" * 14 + \"┴\" + \"─\" * 8 + \"┴\" + \"─\" * 22 + \"┘\")\n",
    "    print()\n",
    "    \n",
    "    # 5. 业绩汇总\n",
    "    overall_completion = total_sales / total_target\n",
    "    avg_sales = total_sales / len(sales_data)\n",
    "    over_target_ratio = over_target_count / len(sales_data)\n",
    "    \n",
    "    print(\"业绩汇总:\")\n",
    "    print(f\"• 总销售额: ¥{total_sales:,.0f} (目标: ¥{total_target:,.0f})\")\n",
    "    print(f\"• 整体完成率: {overall_completion:.1%}\")\n",
    "    print(f\"• 超额完成人数: {over_target_count}人 (占比: {over_target_ratio:.1%})\")\n",
    "    print(f\"• 平均销售额: ¥{avg_sales:,.0f}\")\n",
    "    print()\n",
    "    \n",
    "    # 6. 最佳和最低销售员\n",
    "    best_performer = max(sales_data, key=lambda x: x[\"sales\"])\n",
    "    worst_performer = min(sales_data, key=lambda x: x[\"sales\"])\n",
    "    \n",
    "    print(f\"最佳销售员: {best_performer['name']} ({best_performer['region']}) - ¥{best_performer['sales']:,.0f}\")\n",
    "    print(f\"最低销售员: {worst_performer['name']} ({worst_performer['region']}) - ¥{worst_performer['sales']:,.0f}\")\n",
    "    print()\n",
    "    \n",
    "    # 7. 报表尾部\n",
    "    print(\"━\" * 79)\n",
    "    print(f\"报表生成完成 | 数据统计日期: {report_date:%Y-%m-%d}\")\n",
    "\n",
    "# 生成报表\n",
    "generate_sales_report()\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
